package cn.lili.modules.serviceimpl;

import cn.lili.common.vo.ResponseBean;
import cn.lili.modules.entity.*;
import cn.lili.modules.enums.ReadTypeEnum;
import cn.lili.modules.exception.MyAssert;
import cn.lili.modules.mapper.AppReadMapper;
import cn.lili.modules.service.AppReadService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;


/**
 * @author:xiangqian
 * @date: 2024/3/8 20:30
 */
@Service
public class AppReadServiceImpl extends ServiceImpl<AppReadMapper, AppRead> implements AppReadService {

    /**
     * 根据用户ID查询阅读记录
     *
     * @param userId 用户ID
     * @return 阅读记录
     */
    @Override
    public AppRead getAppReadOnSave(String userId) {
        //查询
        LambdaQueryWrapper<AppRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppRead::getUser_id, userId);
        queryWrapper.last("limit 1");
        AppRead appRead = this.getOne(queryWrapper);

        //如果为空则构建
        if (appRead == null) {
            appRead = AppRead.builder().user_id(userId).comment_number(0).follow_number(0).give_number(0).share_number(0).build();
            this.save(appRead);
        }
        return appRead;
    }

    /**
     * 更新点赞数量
     *
     * @param userId 用户ID
     * @param type   类型 {@link cn.lili.modules.enums.ReadTypeEnum}
     * @param number 数量 数量为-1则累加
     * @return 更新是否成功
     */
    @Override
    public ResponseBean updateAppRead(String userId, Integer type, Integer number) {
        AppRead appRead = getAppReadOnSave(userId);
        ReadTypeEnum readTypeEnum = ReadTypeEnum.getByCode(type);
        MyAssert.notNull(readTypeEnum, "处理类型不存在");

        //根据类型处理
        switch (readTypeEnum) {
            //评价
            case COMMENT:
                appRead.setComment_number(number == -1 ? appRead.getComment_number() + 1 : number);
                break;
            //点赞
            case GIVE:
                appRead.setGive_number(number == -1 ? appRead.getGive_number() + 1 : number);
                break;
            //转发
            case SHARE:
                appRead.setShare_number(number == -1 ? appRead.getShare_number() + 1 : number);
                break;
            //关注
            case FOLLOW:
                appRead.setFollow_number(number == -1 ? appRead.getFollow_number() + 1 : number);
                break;
            default:
                break;
        }
        this.updateById(appRead);
        return ResponseBean.success("更新成功");
    }
}
